// const db = require('dmdb');
import db from 'dmdb';

var pool, conn;

// 达梦数据库连接配置
const config = {
  host: '172.31.3.26',
  // host: '10.3.117.219',
  port: 5236,
  user: 'FSSL',
  password: 'Fssl@2024',
  database: 'AGCLOUD'
};

//创建连接池
async function createPool() {
	try {
		return db.createPool({
			connectString: `dm://${config.user}:${config.password}\@${config.host}:${config.port}?autoCommit=false`,
            poolMax: 10,
            poolMin: 1
        });
  } catch (err) {
		throw new Error("createPool error: " + err.message);
	}
}
// 
//获取数据库连接
async function getConnection() {
	try {
		return pool.getConnection();
	} catch (err) {
		throw new Error("getConnection error: " + err.message);
	}
}

// 处理数据库查询结果
function handleResult(data) {
	const { metaData, rows } = data;

  const result = [];

  rows.map(item => {
    if (item) {
      const obj = {}

      item.map((child, childIndex) => {
        obj[metaData[childIndex].name] = child
      })

      result.push(obj)
    }
  })

  return result
}

// 执行SQL查询
async function executeQuery(sql) {
  pool = await createPool();
  conn = await getConnection();

  try {
		var result = await conn.execute(sql);
    result = handleResult(result);

		return result;
	} catch (err) {
		throw new Error("queryTable error: " + err.message);
	}
}

// SQL注入防护函数
const validateSql = (sql) => {
    // 检查是否包含危险的SQL关键字
    const dangerousKeywords = [
      /;\s*DROP/i,
      /;\s*DELETE/i,
      /;\s*UPDATE/i,
      /;\s*INSERT/i,
      /;\s*CREATE/i,
      /;\s*ALTER/i,
      /;\s*TRUNCATE/i
    ];
  
    if (dangerousKeywords.some(keyword => keyword.test(sql))) {
      throw new Error('检测到不安全的SQL语句');
    }
    return sql;
  };

export default async (ctx) => {
    const { sql } = ctx.request.body;

    // 参数验证
    if (!sql || typeof sql !== 'string') {
        ctx.throw(400, 'SQL语句不能为空且必须是字符串类型');
    }

    // SQL注入防护
    try {
        validateSql(sql);
    } catch (err) {
        ctx.throw(403, err.message);
    }

    try {
        // 执行查询
        const result = await executeQuery(sql);
        
        // 规范化响应格式
        ctx.body = {
            code: 200,
            success: true,
            message: 'success',
            data: result || []
        };
    } catch (err) {
        // 根据错误类型返回不同的状态码
        const status = err.code === 'CONNECTION_ERROR' ? 503 : 500;
        ctx.throw(status, `查询执行失败: ${err.message}`);
    }
}